import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/Home.vue'
import IndexView from '../views/IndexView.vue'
import UserView from '../views/UserView.vue'
import BookView from '@/views/BookView.vue'
import test from '@/views/testView.vue'
import loginView from '@/views/loginView.vue' 
import notfind from '@/views/404view.vue'
import BorrowView from '@/views/BorrowView.vue'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      redirect: '/index',
      children: [
        {
          path: '/index',
          name: 'index',
          component: IndexView,
        },
        {
          path: '/user',
          name: 'user',
          component: UserView,
          meta: { requiresAuth: true, roles: ['admin', 'teacher'] }
        },
        {
          path: '/book',
          name: 'book',
          component: BookView,
          meta: { requiresAuth: true, roles: ['teacher','admin']}
        },
        {
          path: '/borrow',
          name: 'borrow',
          component: BorrowView,
          meta: { requiresAuth: true, roles: ['student','teacher'] }
        },
        {
          path: '/test',
          name: 'test',
          component: test,
          meta: { requiresAuth: true, roles: ['student'] }
        }
      ],
    },
    {
      path: '/login',
      name: 'login',
      component: loginView,
    },
    {
      path: '/404',
      name: '404',
      component: notfind,
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404'
    }
  ],
})


// 导航守卫，检查用户是否已登录
router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta?.requiresAuth);
  const userType = sessionStorage.getItem('type');

  if (requiresAuth) {
    if (!userType) {
      // 用户未登录，重定向到登录页面
      next('/login');
    } else {
      // 用户已登录，检查角色权限
      const hasAccess = to.matched.some(record => {
        const roles = record.meta?.roles;
        return Array.isArray(roles) && roles.includes(userType);
      });
      if (hasAccess) {
        next();
      } else {
        // 用户没有权限访问该页面，重定向到 404 页面
        next('/404');
      }
    }
  } else {
    // 页面不需要身份验证，允许访问
    next();
  }
});

export default router